<?php
namespace app\task\controller;
use app\task\logic\CpFormUserMonthLogic;

/**
 * 社区巡店用户报表（月）api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/25
 * Time: 16:11
 */
class CpFormUserMonth extends Base {

    public function __construct(){
        parent::__construct();
        $this->cfum_logic = new CpFormUserMonthLogic();
    }

    /**
     * 处理报表
     * @return \think\response\Json
     */
    public function deal_form(){
        $now_time = date('Y-m-d H:i:s');

        $maps = [];
        $maps[] = ['id','>',1];
        $openids = model('user')->get_column($maps,'openid');
        foreach($openids as $k => $v){
            //获取需要计算的时间
            $r = $this->cfum_logic->get_count_time($v,$now_time);
            if(!$r['code']){
                continue;
            }
            $start_time = $r['data']['start_time'];
            $end_time = $r['data']['end_time'];
            $timeid = $r['data']['timeid'];

            //查找该月是否已计算数据
            $maps = [];
            $maps[] = ['openid','=',$v];
            $maps[] = ['timeid','=',$timeid];
            $cfum_detail = model('cp_form_user_month')->get_detail($maps,'id');

            //计算用户社区已巡店次数
            $cp_user_num = $this->cfum_logic->count_cp_user_num($v,$start_time,$end_time);

            $cfum_data = [];
            $cfum_data['openid'] = $v;
            $cfum_data['cp_user_num'] = $cp_user_num;
            $cfum_data['timeid'] = $timeid;

            //更新数据
            if(empty($cfum_detail)){
                $r = model('cp_form_user_month')->insert($cfum_data);
            }else{
                $maps = [];
                $maps[] = ['id','=',$cfum_detail['id']];
                $r = model('cp_form_user_month')->where($maps)->update($cfum_data);
            }
        }
        return json($this->cfum_logic->get_response(1,'处理用户报表，日期：' . $now_time));
    }
}